package westh.ilib.struts.action.researcher;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.mule.extras.client.MuleClient;
import org.mule.umo.UMOMessage;

import westh.config.Config;
import westh.ilib.bean.researcher.Article;

public class GetResearcherResourceAction extends Action {
	private final static Log log = LogFactory.getLog(GetResearcherResourceAction.class);
	//get clouds Ip address
	String localhostUrl = Config.get("localhostUrl");
	String remoteUrl = Config.get("remoteUrl");

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		DynaActionForm f = (DynaActionForm) form;
		String researcherId = f.getString("researcherId");
		JSONObject inputObj = new JSONObject();
		inputObj.put("researcherId", researcherId);
		String input = inputObj.toString();

		// jSon-String
		String outString = "";
		try {
			MuleClient client = new MuleClient();
			UMOMessage umo = client.send("axis:http://"+localhostUrl+":4381/LIBJson/iDlibJson?method=getResearcherRscList",	input, null);
			outString = (String) umo.getPayload();
	//		log.debug("getResearcherRscList outString=" + outString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		String retCode = "";
		String retMsg = "";
		JSONObject jsonOut = JSONObject.fromObject(outString);
		retCode = jsonOut.getString("retCode");
		log.debug("reCode &&&&&&&&&&&=" + retCode);
		List listArticle = null;
		if (retCode.equals("1500")) {
			// get article info
			JSONArray result = jsonOut.getJSONArray("result");
			log.debug("result****************=" + result);
			int size = result.size();
			listArticle = new ArrayList();
			for (int i = 0; i < size; ++i) {
				JSONObject articleObj = result.getJSONObject(i);
				Article art = new Article();
				art.setArticleId(articleObj.getString("rscId"));
				art.setArticleName(articleObj.getString("rscName"));
				art.setPublishDate(articleObj.getString("rscPublishDate"));
				art.setAuthors(articleObj.getString("rscAuthor"));
				listArticle.add(art);
			}
			request.setAttribute("listArticle", listArticle);
			return mapping.findForward("succ");
		} else if (retCode.equals("1501")) {
			retMsg = jsonOut.getString("retMsg");
			request.setAttribute("info", retMsg);
			return mapping.findForward("fail");
		}
		return mapping.findForward("fail");
	}

}
